package com.liu.jd_demo.utils;

import com.liu.jd_demo.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author QS.Liu
 * @date 2020/6/29/21:04
 */
public class HtmlUtils {

    public List<Content> parseJD(String keyword) throws IOException {
        String key = "java";
        if (keyword != null) key = keyword;
        //获取请求
        String url = "https://search.jd.com/Search?keyword=" + key;
        //解析网页
        Document document = Jsoup.parse(new URL(url), 30000);//返回的就是js界面
        //所有在js中使用的方法在这里都可以使用
        Element j_goodsList = document.getElementById("J_goodsList");

        ArrayList<Content> arrayList = new ArrayList<>();
        // 获取所有的 li 标签
        Elements lis = j_goodsList.getElementsByTag("li");
        for (Element li : lis) {
            String img = li.getElementsByTag("img").eq(0).attr("src");
            //String img = li.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
            String price = li.getElementsByClass("p-price").eq(0).text();
            String title = li.getElementsByClass("p-name").eq(0).text();
            System.out.println(title+"--"+img +"--"+price);
            arrayList.add(new Content(title,img,price));
        }
        return arrayList;
    }

}
